<template>
  <div class="change-password">
    <el-dialog
      :title="dialogTitle"
      v-model="$mapStore.passWordShow"
      width="20%"
          >
      <hr style="margin-bottom: 10px;" color="#f0f0f0">
      <div class="dialog-content">
        <span><h3>用户名:</h3></span>
        <el-input v-model="username" placeholder="请输入用户名"></el-input>
      <span><h3>旧密码:</h3></span>
      <el-input v-model="oldPassword" type="password" show-password  placeholder="请输入旧密码"></el-input>
      <span><h3>新密码:</h3></span>
      <el-input v-model="newPassword" type="password" show-password  placeholder="请输入新密码"></el-input>
      <div class="button-group" style="display: flex;gap: 20px; justify-content: flex-end;">
          <el-button type="primary" @click="changePassword">确定</el-button>
          <el-button type="default" @click="cancelPassword">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref,onMounted} from "vue"
import { ElMessage } from 'element-plus'
// import {axios} from "../../reuqest/Http.js"
import axios from 'axios'
import { useLoginStore } from "../../stores/counter.js";
import { useMapStore } from "../../stores/map.js";
const $store = useLoginStore()
const $mapStore = useMapStore()
const dialogTitle = ref("修改密码") 
const username = ref("")
const oldPassword = ref("")
const newPassword = ref("")
onMounted(() => {
  username.value = $store.currentUser.username
})
//修改密码
const changePassword =async () => {
  //判断信息是否有空值
  if (username.value == "" || oldPassword.value == "" || newPassword.value == "") {
    ElMessage.error('请填写完整信息')
    return
  }//获取普通用户信息
  const resUser=await axios.get(`/api/user?type=common`)
  //获取当前用户id和密码
  const userId=resUser.result.filter(item => item.username == username.value)[0].id
  const user_password=resUser.result.filter(item => item.username == username.value)[0].password
  console.log(userId)
  console.log(user_password)
  //判断旧密码是否正确,如果正确,修改密码
  if(oldPassword.value!=user_password){
    ElMessage({
    message: '旧密码错误',
    type: 'warning',
  })
    return
  }else{
    axios.post('/api/change',{
    type:"common",
    id:userId,
    password:newPassword.value,
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
    message: '修改成功',
    type: 'success',
  })
    }
  })
  localStorage.setItem("currentUser", JSON.stringify({
    username: username.value,
    password: newPassword.value,
    type: "common"
  }))
  }
  //关闭弹窗
  $mapStore.setPasswordShow(false)
  oldPassword.value = ""
  newPassword.value = ""
}
//取消修改密码
const cancelPassword = () => {
  oldPassword.value = ""
  newPassword.value = ""
  $mapStore.setPasswordShow(false)
}
</script>

<style>
.dialog-content{
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.el-dialog__title {
  color: #303133;
  font-size: 18px;
  font-weight: bolder;
}
</style>